package me.itblog.mvc.filter;

import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by infi.he on 2015/12/3.
 */
public class LoginFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    List<Pattern> authcPatternList = new ArrayList<>();
    String loginurl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String authc = filterConfig.getInitParameter("authc");
        if (Strings.isNotBlank(authc)) {
            String[] split = authc.split(",");
            for (String s : split) {
                authcPatternList.add(Pattern.compile(s));
            }
        }
        loginurl = filterConfig.getInitParameter("loginurl");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String requestURI = req.getRequestURI();
        boolean isLogin = false;
        for (Pattern pattern : authcPatternList) {
            Matcher matcher = pattern.matcher(requestURI);
            isLogin = isLogin || matcher.find();
        }
        if(isLogin){
            if(requestURI.equals("/admin/ajaxLogin")||requestURI.equals("/admin/login")){
                isLogin = false;
            }
        }

        logger.info("url>>>>" + requestURI + "  --->isLogin>>" + isLogin);
        if (!isLogin) {
            chain.doFilter(request, response);
        } else {
            if (req.getSession().getAttribute("me") == null) {
                //ajax
                if (req.getHeader("x-requested-with") != null
                        && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                    NutMap re = new NutMap().setv("ok", false).setv("msg", "没有登录，请登录!");
                    try {
                        Json.toJson(resp.getWriter(), re);
                    } catch (IOException e) {
                    }
                } else {
                    resp.setHeader("Cache-Control", "no-store");
                    resp.setDateHeader("Expires", 0);
                    resp.setHeader("Prama", "no-cache");
                    resp.sendRedirect(loginurl + "?service=" + requestURI);
                }
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
